package com.xjiye_test.payServer.servletGroup.shemmapay;

import com.xiaoleilu.hutool.db.Entity;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.xjiye_test.payServer.dao.SmfOrderDao;
import com.xjiye_test.payServer.pojo.SmfPayInfo;
import com.xjiye_test.payServer.serverletUtil.HttpUtil;
import com.xjiye_test.payServer.serverletUtil.PaySignature;
import com.xjiye_test.payServer.serverletUtil.PlatformPayException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

public class RefundSmf extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        String reStr="";
        try {
            SmfOrderDao smfdao=new SmfOrderDao();
            List<Entity> orders =smfdao.getOrderByOrderNo(req.getParameter("orderNo"));
            if(orders.size()==0){
                reStr="订单不存在";
            }
            if(orders.size()==1){
                reStr=refundToSmf(orders.get(0));
            }
            if(orders.size()==2){
                reStr="订单已经退过款";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            out.print(reStr);
            out.flush();
        }
    }

    public String refundToSmf(Entity order){
        Map<String,Object> orderPayMap=new TreeMap<>();
        orderPayMap.put("pay_no",order.getStr("payNo"));
        orderPayMap.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String biz_content="";
        for(Map.Entry var:orderPayMap.entrySet()){
            if(null!=var.getValue().toString()&&var.getValue().toString().length()>0){
                biz_content+=var.getKey()+"="+var.getValue()+"&";
            }
        }
        biz_content= StrUtil.sub(biz_content,0,-1);
        try {
            biz_content= PaySignature.rsaEncrypt(biz_content,GlobalVariable.publicKey,GlobalVariable.charset);
        } catch (PlatformPayException e) {
            e.printStackTrace();
            return "fail";
        }
        String sign= null;
        try {
            sign = PaySignature.rsaSign(biz_content, GlobalVariable.privateKey,GlobalVariable.charset,GlobalVariable.signType);
        } catch (PlatformPayException e) {
            e.printStackTrace();
            return "fail";
        }
        Map<String,String> reqVar=new HashMap<>();
        reqVar.put("biz_content",biz_content);
        reqVar.put("sign",sign);
        reqVar.put("sign_type",GlobalVariable.signType);
        reqVar.put("charset",GlobalVariable.charset);
        reqVar.put("s_id",GlobalVariable.sID);
        Map<String,String> header=new HashMap<>();
        header.put("Content-Type","application/json");
        try {
            HttpResponse result = HttpUtil.getInstance().doPost(GlobalVariable.payUrl+"/refund", JSONUtil.toJsonStr(reqVar),header);
            if (result.getStatusLine().getStatusCode() == 200) {
                JSONObject json=JSONUtil.parseObj(EntityUtils.toString(result.getEntity()));
                if("100".equals(json.getStr("msgcode"))){
                    SmfOrderDao smfdao=new SmfOrderDao();
                    SmfPayInfo pay= new SmfPayInfo();
                    pay.setAmount(order.getInt("amount"));
                    pay.setOrder_no(order.getStr("order_no"));
                    pay.setSubject(order.getStr("subject"));
                    pay.setPay_type(order.getStr("pay_type"));
                    pay.setPay_channel(order.getStr("pay_channel"));
                    pay.setMemo(order.getStr("memo"));
                    pay.setNotify_url("");
                    pay.setAuth_code("");
                    smfdao.addSmfRefundInfo(pay,GlobalVariable.sID,order.getStr("payNo"));
                }
                return json.toString();
            }else {
                return EntityUtils.toString(result.getEntity());
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return "fail";
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        } catch (SQLException e) {
            e.printStackTrace();
            return "fail";
        }
    }

}
